
import { defineStore } from 'pinia'
import { characterAPI } from '../api/characters.js'

export const useCharacterStore = defineStore('character', {
  state: () => ({
    character: { // 提供一个默认的空对象或合适的初始值
        name: '',
        image_url: '',
        background: '',
        preferences: {},
      },
    isLoading: false,
    error: null,
  }),
  actions: {
    async getCharacterById(id) {
      this.isLoading = true
      this.error = null
      try {
        const response = await characterAPI.getCharacter(id)

        if (!response) {
          throw new Error('Character data is empty')
        }

        // 将 preferences 从字符串转为对象
        if (typeof response.preferences === 'string') {
          response.preferences = JSON.parse(response.preferences)
        }

        this.character = response
      } catch (error) {
        this.error = error.message
        this.character = null
        throw error
      } finally {
        this.isLoading = false
      }
    },
  },
})